package com.tianci.appstore.ui.list.upgrade;

import android.content.Context;
import android.os.Bundle;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import com.coocaa.x.framework.utils.LogUtils;
import com.tianci.appstore.R;
import com.tianci.appstore.controller.manager.UpdateManagerController;
import com.tianci.appstore.controller.manager.UpdateManagerController.ACTION;
import com.tianci.appstore.ui.SkinManager;
import com.tianci.appstore.ui.data.SkyAppBaseData;
import com.tianci.appstore.ui.data.SkyAppDetailData.AppAction;
import com.tianci.appstore.ui.data.SkyAppDetailData.AppStatus;
import com.tianci.appstore.ui.data.SkyListAppData;
import com.tianci.appstore.ui.data.SkyListAppData.ListType;
import com.tianci.appstore.ui.data.SkyListProgressData;
import com.tianci.appstore.ui.detail.AppDownloadListener;
import com.tianci.appstore.ui.dialog.CommonAppOpDialog;
import com.tianci.appstore.ui.dialog.UpdateDialog;
import com.tianci.appstore.ui.list.ListFlipper;
import com.tianci.appstore.ui.list.ListStatusBlock;
import com.tianci.appstore.ui.list.download.DownloadListView;
import com.tianci.appstore.ui.util.UICommon;
import com.tianci.appstore.ui.widget.ColorButton;
import com.tianci.appstore.ui.widget.OnButtonClickListener;
import com.tianci.appstore.ui.widget.SkyCustomLayout;
import com.tianci.appstore.utils.SkyConstants;

import java.util.HashMap;
import java.util.List;

public class UpgradeListView extends DownloadListView
        implements UpgradeListDataListener, AppDownloadListener, OnButtonClickListener {
    private Button refreshAllBtn;
    public static final String UPGRADE_ALL = "更新";

    private static final int UPDATE_UPGRADE_INFO = 20;

    public UpgradeListView(Context context) {
        super(context);
        this.listType = ListType.UPGRADE_APP_LIST;
        titleText.setText(R.string.app_upgrade);
        // TODO Auto-generated constructor stub
        setLoadingVisible(true);
    }

    @Override
    protected void initController() {
        // TODO Auto-generated method stub
        UpdateManagerController.getInstance().init(this, this, this);
    }

    @Override
    protected void initTopRightLayout() {
        LinearLayout rightTopLayout = new LinearLayout(mContext);
        rightTopLayout.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);

        refreshAllBtn = UICommon.newButton(mContext, rightTopTextSize, R.color.btnColor);
        refreshAllBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (v.getTag() != null) {
                    ACTION action = (ACTION) v.getTag();
                    UpdateManagerController.getInstance().handleAction(action, null);
                }
            }
        });
        refreshAllBtn.setText(R.string.pause_all);
        SkinManager.setBackground(refreshAllBtn, R.drawable.search_selector);
        //refreshAllBtn.setPadding(SkyConstants.Div(20), SkyConstants.Div(18), SkyConstants.Div(20), SkyConstants.Div(18));
        rightTopLayout.addView(refreshAllBtn);

        LayoutParams topRightParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.TOP | Gravity.RIGHT);
        topRightParams.setMargins(0, SkyConstants.Div(85), SkyConstants.Div(102), 0);
        this.addView(rightTopLayout, topRightParams);
    }

    @Override
    public void destroyController() {
        // TODO Auto-generated method stub
        UpdateManagerController.getInstance().destroy();
        super.destroyController();
    }

    @Override
    protected void handleOtherMsg(Message msg) {
        // TODO Auto-generated method stub
        switch (msg.what) {
            case UPDATE_UPGRADE_INFO:
                Bundle bundle = msg.getData();
                refreshUpgradeInfo(bundle.getString("appId"),
                        bundle.getString("version"), bundle.getString("info"));
                break;
        }
        super.handleOtherMsg(msg);
    }

    @Override
    public void onRefreshUpgradeInfo(String appId, String versionName, String upgradeInfo) {
        // TODO Auto-generated method stub
        Message msg = mainHandler.obtainMessage(UPDATE_UPGRADE_INFO);
        Bundle bundle = new Bundle();
        bundle.putString("appId", appId);
        bundle.putString("version", versionName);
        bundle.putString("info", upgradeInfo);
        msg.setData(bundle);
        mainHandler.sendMessage(msg);
    }

    protected void refreshUpgradeInfo(String appId, String versionName, String upgradeInfo) {
        if (infoDialog != null) {
            if (appId != null && appId.equals(infoDialog.getAppId())) {
                infoDialog.setContent(versionName, upgradeInfo);
            }
        }
    }

    @Override
    protected void refreshStatus(String appId, AppStatus status) {
        for (int i = 0; i < ListFlipper.VIEW_PAGE_COUNT; i++) {
            SkyCustomLayout child = (SkyCustomLayout) listFlipper.getChildAt(i);
            for (View view : child.getChildViews()) {
                ListStatusBlock block = (ListStatusBlock) view;
                if (block.getDataId() != null && block.getDataId().equals(appId)) {
                    block.updateStatus(status);
                    break;
                }
            }
        }
        if (dialog != null && dialog.isShowing()) {
            if (clickedData.getId().equals(appId)) {
                clickedAppStatus = status;
                dialog.refreshContent(getContentByStatus(status));
                dialog.refreshButton(getActionByStatus(status, 0), 0, false);
                dialog.refreshButton(getActionByStatus(status, 1), 1, true);
            }
        }
    }

    @Override
    protected void refreshDataList(int activeCount, int pauseCount,
                                   int otherCount, List<SkyListAppData> dataList) {
        if (dataList == null || dataList.size() == 0) {
            setEmptyTipVisible(true, mContext.getResources().getString(R.string.no_upgrading_task));
            setButtonEnabled(refreshAllBtn, false, R.string.no_upgrading, ACTION.DELETE);
            return;
        }
        refreshActiveCount(activeCount, pauseCount, otherCount);
        setLoadingVisible(false);
        setEmptyTipVisible(false, null);

        if (lastFocusPageIndex != -1 && lastFocusIndex != -1) {
            mController.setDataList(dataList, lastFocusPageIndex, lastFocusIndex);
            lastFocusPageIndex = -1;
            lastFocusIndex = -1;
        } else {
            mController.setDataList(dataList);
            resetFocus();
        }
        if (refreshAllBtn.isEnabled())
            refreshAllBtn.requestFocus();
    }

    @Override
    protected void refreshActiveCount(int activeCount, int pauseCount, int otherCount) {
        LogUtils.d("count", "activeCount = " + activeCount + ", pauseCount = " + pauseCount +
                ", not downloaded count = " + otherCount);
        if (activeCount > 0) {
            setButtonEnabled(refreshAllBtn, true, R.string.pause_all, ACTION.PAUSE_ALL);
        } else {
            if (pauseCount > 0)
                setButtonEnabled(refreshAllBtn, true, R.string.continue_all, ACTION.UPDATE_ALL);
            else {
                if (otherCount > 0)
                    setButtonEnabled(refreshAllBtn, true, R.string.upgrade_all, ACTION.UPDATE_ALL);
                else
                    setButtonEnabled(refreshAllBtn, false, R.string.no_upgrading, ACTION.DELETE);
            }
        }
    }

    protected void setButtonEnabled(Button btn, boolean enabled, int strId, ACTION action) {
        btn.setEnabled(enabled);
        btn.setTag(action);
        if (enabled)
            btn.setAlpha(1.0f);
        else {
            btn.setAlpha(UICommon.disableAlpha);
            resetFocus();
        }
        btn.setText(strId);
        btn.setFocusable(enabled);
    }

    protected UpdateDialog infoDialog;
    protected CommonAppOpDialog dialog;
    protected AppStatus clickedAppStatus;
    protected SkyListProgressData clickedData;
//    protected int clickedIndex = -1;

    // 处理某应用点击事件
    @Override
    public void onBlockClicked(View v, SkyListAppData data, int index) {
        // TODO Auto-generated method stub
        lastFocusPageIndex = mController.getCurrentPageIndex();
        lastFocusIndex = index;
        clickedData = (SkyListProgressData) data;
        clickedAppStatus = clickedData.getStatus();
        if (clickedAppStatus == AppStatus.NOT_DOWNLOADED) {
            if (infoDialog == null) {
                infoDialog = new UpdateDialog(mContext);
                infoDialog.setButtonClickListener(this);
            }
            infoDialog.setIconTitle(data, data.getTitle());
            UpdateManagerController.getInstance().handleAction(ACTION.SHOW_DETAIL, clickedData);
            infoDialog.show();
        } else {
            if (dialog == null) {
                dialog = new CommonAppOpDialog(mContext);
                dialog.setButtonClickListener(this);
            }

            dialog.setData(data, getContentByStatus(clickedAppStatus));
            AppAction action = getActionByStatus(clickedAppStatus, 0);
            if (action == AppAction.ACTION_CANCEL) {
                ColorButton btn = new ColorButton(mContext, R.string.cancel_upgrade,
                        R.drawable.btn_gray, R.drawable.btn_gray_focus);
                dialog.addButton(btn, 0, false);
            } else {
                dialog.addButton(action, 0, false);
            }
            dialog.addButton(getActionByStatus(clickedAppStatus, 1), 1, true);
            try {
                dialog.show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected AppAction getActionByStatus(AppStatus status, int index) {
        // TODO Auto-generated method stub
        if (status == AppStatus.NOT_DOWNLOADED) {
            return AppAction.ACTION_DOWNLOAD;
        }
        return super.getActionByStatus(status, index);
    }

    @Override
    protected String getContentByStatus(AppStatus status) {
        String content = "";
        switch (status) {
            case DOWNLOADING:
                content = mContext.getResources().getString(R.string.upgrading_tip);
                break;
            case DOWNLOAD_PAUSED:
                content = mContext.getResources().getString(R.string.upgrade_paused_tip);
                break;
            case WAITING:
                content = mContext.getResources().getString(R.string.upgrade_wait_tip);
                break;
            default:
                return super.getContentByStatus(status);
        }
        return content;
    }

    // 处理弹出框button点击事件
    @Override
    public void onClick(int index) {
        // TODO Auto-generated method stub
        AppAction action = getActionByStatus(clickedAppStatus, index);
        if (action == AppAction.ACTION_PAUSE ||
                action == AppAction.ACTION_CONTINUE ||
                action == AppAction.ACTION_INSTALL ||
                action == AppAction.ACTION_DELETE ||
                action == AppAction.ACTION_CANCEL ||
                action == AppAction.ACTION_PRIORITIZE ||
                action == AppAction.ACTION_DOWNLOAD) {
            ACTION realAction = ACTION.PAUSE;
            if (action == AppAction.ACTION_CONTINUE ||
                    action == AppAction.ACTION_DOWNLOAD)
                realAction = ACTION.START;
            else if (action == AppAction.ACTION_INSTALL)
                realAction = ACTION.INSTALL;
            else if (action == AppAction.ACTION_DELETE
                    || action == AppAction.ACTION_CANCEL)
                realAction = ACTION.DELETE;
            else if (action == AppAction.ACTION_PRIORITIZE)
                realAction = ACTION.TO_FIRST;
            LogUtils.d("hhhh", "send cmd to lyx, realAction = " + realAction);
            UpdateManagerController.getInstance().handleAction(realAction, clickedData);
        }
        if (action == AppAction.ACTION_DOWNLOAD) {
            if (infoDialog != null)
                infoDialog.hide();
        } else {
            if (dialog != null)
                dialog.hide();
        }
    }

    @Override
    public void onItemAudioMatch(SkyAppBaseData data, int index) {
        ACTION action = ACTION.START;
        UpdateManagerController.getInstance().handleAction(action, (SkyListProgressData) data);
    }

    @Override
    public void onAudioMatch(String name) {
        String action = refreshAllBtn.getTag().toString();
        if (name.equals(UPGRADE_ALL) && action.equals(ACTION.UPDATE_ALL.toString())) {
            UpdateManagerController.getInstance().handleAction(ACTION.UPDATE_ALL, null);
        }
    }

    @Override
    public HashMap<String, String[]> addExtraCommand(HashMap<String, String[]> current) {
        current.put(UPGRADE_ALL, new String[]{"全部更新", "更新全部"});
        return current;
    }

}
